/**
 * @Title: LoginSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: 登录
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月25日 下午4:13:11
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.LoginReq;
import com.jason.fingerprint.beans.LoginResp;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.utils.CodecUtils;

import java.util.List;

import android_serialport_api.FingerprintReader;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * @ClassName: LoginSyncLogic
 * @Description: 登录
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月25日 下午4:13:11
 */
public class LoginSyncLogic extends Logic {

	public static final int LOGIN_FINGERPRINT = 1;// 指纹登录
	public static final int LOGIN_ACCOUNT = 2;// 账号登录

	private static final String TAG = "LoginSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack;// 是否有回调，此需要Handle
	private int mCurrentIndex = 1;// 当前页
	private Message mMessage;
	private Context mContext;
	private LoginReq mLoginReq;// 请求参数
	private int mType;
	private FingerprintReader mAsyncFingerprint;
	private int mFingerId = 0;
	private int mFingerCount = 0;
	private int mFingerCurrent = -1;
	private List<FingerPrintBean> mFingerPrintBeans;
	private List<UserBean> values;
	private int totalRowsCount;

	public LoginSyncLogic() {

	}

	public LoginSyncLogic(AppContext appContext, Context context,
			Handler handler, boolean isCallBack, LoginReq loginReq) {
		super(appContext);
		this.mHandler = handler;
		this.mContext = context;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mLoginReq = loginReq;
	}

	@Override
	public void execute() {
		Log.i(TAG, "execute");
		try {
			mKjdb.deleteTable(UserBean.class);
			//删除工作人员的指纹信息
			mKjdb.deleteByWhere(FingerPrintBean.class, "type = 2");
		} catch (Exception e) {

		}
		datbLoginSync();
	}

	@Override
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	// 档案同步
	private void datbLoginSync() {
		Log.i(TAG, "mLoginReq---->" + mLoginReq.toString());
		mType = mLoginReq.getType();
		String url = mLoginReq.getUrl();
		mParams = new RequestParams();
		mParams.addFormDataPart("type", String.valueOf(mType));
		// 指纹登录
		mParams.addFormDataPart(AppGlobal.HTTP_PARAM_IMEI, mImei);
		if (mType == LOGIN_ACCOUNT) {
			// 账号登录
			mParams.addFormDataPart("loginName", mLoginReq.getLoginName());
			mParams.addFormDataPart("loginPwd", mLoginReq.getLoginPwd());
		}
		mParams.addFormDataPart(AppGlobal.HTTP_PARAM_CURRENTINDEX,
				String.valueOf(mCurrentIndex));
		
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->API:" + mParams.toString());
		HttpRequest.post(url, mParams, new BaseHttpRequestCallback<String>() {

			@Override
			protected void onSuccess(String o) {
				super.onSuccess(o);
				if (o == null){
					mMessage.what = UIHelper.LOGIN_FAIL;
					mMessage.obj ="登录失败，请重试";
					return;
				}
				String result = CodecUtils.base64Decode(o);
				Log.i(TAG, "----->Result:" + result);
				Gson gson = new GsonBuilder().create();
				LoginResp loginResp = gson.fromJson(result, LoginResp.class);
				if (loginResp != null) {
					Log.i(TAG, loginResp.toString());
					values = loginResp.getValues();
					totalRowsCount = loginResp.getTotalRowsCount();
					if (loginResp.isSuccess()){
						if (values != null && !values.isEmpty()) {
							// 保存信息到数据库
							for (UserBean userBean : values) {
								// 保存工作人员信息
								if (userBean != null) {
									String userId = String.valueOf(userBean
											.getUserId());
									String userName = userBean.getUserName();
									String fp1 = userBean.getFingerprint1();
									String fp2 = userBean.getFingerprint2();
									mKjdb.save(userBean);
									// 保存工作人员指纹信息
									mKjdb.save(new FingerPrintBean(userId,
											userName, fp1, 2, 1));
									mKjdb.save(new FingerPrintBean(userId,
											userName, fp2, 2, 2));
								}
							}
							if (!loginResp.isLastPage()) {
								mCurrentIndex++;
								datbLoginSync();
							} else {
								mMessage.what = UIHelper.LOGIN_SUCCESS;
								mMessage.arg1 = totalRowsCount;
								mMessage.obj = values;
								send();
							}
						} else {
							mMessage.what = UIHelper.LOGIN_FAIL;
							mMessage.obj = loginResp.getRespMsg();
							send();
						}
					}else {
						mMessage.what = UIHelper.LOGIN_FAIL;
						mMessage.obj = loginResp.getRespMsg();
						send();
					}
				} else {
					mMessage.what = UIHelper.LOGIN_FAIL;
					mMessage.obj = "登录失败,请重新尝试";
					send();
				}
			}


			@Override
			public void onFailure(int errorCode, String msg) {
				super.onFailure(errorCode, msg);
				Log.i(TAG, "----->Result:arg1:" + errorCode + ",arg2:" + msg);
				if (errorCode == UIHelper.HTTP_CODE_TIMEOUT){
					mMessage.what = UIHelper.HTTP_CODE_TIMEOUT;
					mMessage.obj = "网络连接超时";
				}else {
					mMessage.what = UIHelper.LOGIN_FAIL;
					mMessage.obj = "登录失败,请重新尝试";
				}
				send();
			}
		});
	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
